<template>
  <el-row justify="space-between">
    <!-- 搜索栏-->
    <el-col :span="10">
      <el-input
          v-model="empName"
          placeholder="请输入职员名称"
          clearable
          @keyup.enter="search"
      >
      </el-input>
    </el-col>

    <el-col :span="10">
      <el-input
          v-model="account1"
          placeholder="请输入账号"
          clearable
          @keyup.enter="search"
      ></el-input>
    </el-col>

    <!-- 搜索按钮 -->
    <el-col :span="2">
      <el-button type="primary" icon="el-icon-search" @click="search" class="search-button">搜索</el-button>
    </el-col>
    <!--新增按钮-->
    <el-col :span="2">
      <el-button type="primary" @click="openAddDialog">
        <el-icon>
          <Plus/>
        </el-icon>
        新增职员
      </el-button>
    </el-col>
  </el-row>
  <!--表格-->
  <MessageBox2 :page-size="pageSize" :current-page="currentPage" :total="total" :table-data="employeeStore.employees"
               :table-title-list="tableTitleList" :loading="loading" :table-title="tableTitle" :batch-mode="batchMode"
               @current-change="currentPageChange" @size-change="pageSizeChange" @selectionChange="updateSelectedRows">
    <template #title-btn>
      <el-button type="primary" @click="toggleBatchMode">
        {{ batchMode ? "取消批量操作" : "批量操作" }}
      </el-button>
      <el-button
          type="danger"
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
          v-if="batchMode"
      >
        批量删除
      </el-button>
    </template>

    <template v-slot:table-btn>
      <el-table-column label="照片">
        <template #default="{ row }">
          <img
              :src="row.photo"
              alt="员工照片"
              class="preview-image"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button icon="edit" circle plain type="warning" size="mini" @click="openEditDialog(row,0)">编辑</el-button>
          <el-button icon="delete" circle plain type="danger" size="mini" @click="deleteEmployee(row.empId)">删除
          </el-button>
        </template>
      </el-table-column>
    </template>
  </MessageBox2>
  <!--新增员工-->
  <el-dialog title="新增员工" v-model="addDialogVisible">
    <div v-if="!addVisble">
      <el-form :model="newEmployee" label-width="100px">
        <el-form-item label="账号" prop="account" required>
          <el-input v-model="newEmployee.account" placeholder="请输入员工账号"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password" required>
          <el-input v-model="newEmployee.password" placeholder="请输入用户密码"></el-input>
        </el-form-item>

        <el-form-item label="员工类型" prop="type" required>
          <el-select v-model="newEmployee.type" placeholder="请选择员工类型">
            <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="员工姓名" prop="empName" required>
          <el-input v-model="newEmployee.empName" placeholder="请输入员工姓名"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex" required>
          <el-select v-model="newEmployee.sex" placeholder="请选择员工性别">
            <el-option
                v-for="item in sexOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
            <template #footer>
              <el-button v-if="!isAdding" text bg size="small" @click="onAddOption">
                Add an option
              </el-button>
              <template v-else>
                <el-input
                    v-model="optionName"
                    class="option-input"
                    placeholder="input option name"
                    size="small"
                />
                <el-button type="primary" size="small" @click="onConfirm">
                  confirm
                </el-button>
                <el-button size="small" @click="clear">cancel</el-button>
              </template>
            </template>
          </el-select>
        </el-form-item>

        <el-form-item label="员工照片" prop="photo">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/common/upload"
              :show-file-list="true"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
              :on-error="handlePhotoError"
          >
            <div v-if="newEmployee.photo">
              <img :src="newEmployee.photo" class="el-upload-list__item-thumbnail preview-image"
                   alt=""/>
              <div class="photo-actions">
                <el-button size="mini" type="danger" @click="deletePhoto" icon="el-icon-delete" circle>删除</el-button>
              </div>
            </div>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>

        </el-form-item>
        <el-form-item label="电话" prop="empPhone">
          <el-input v-model="newEmployee.empPhone" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newEmployee.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="入职时间" prop="hireTime" required>
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker
                v-model="newEmployee.hireTime"
                type="date"
                placeholder="Pick a day"
                value-format="YYYY-MM-DD"
            />
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="newEmployee.note" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div v-else>
      <el-table :data="regData" stripe>
        <el-table-column label="id" prop="id"/>
        <el-table-column label="account" prop="account"/>
        <el-table-column label="password" prop="password"/>
        <el-table-column label="type">
          <template #default="{ row }">
            <span>
              <!-- 根据 type 显示不同的角色名称 -->
              {{ getRoleName(row.type) }}
            </span>
          </template>
        </el-table-column>
        <!--操作-->
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button @click="openEditDialog(row,1)">将其注册为职员</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="没有数据"/>
        </template>
      </el-table>
    </div>
    <template #footer>
      <el-button @click="handleRegisterData">注册管理</el-button>
      <el-button @click="addDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveEmployee">保存</el-button>
    </template>
  </el-dialog>

  <!--修改对话框-->
  <el-dialog title="编辑员工" v-model="editDialogVisible" width="30%">
    <el-form :model="editData" label-width="100px">
      <el-form-item label="员工账号" prop="account" required>
        <el-input v-model="editData.account"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" required>
        <el-input v-model="editData.password"></el-input>
      </el-form-item>
      <el-form-item label="员工类型" prop="type" required>
        <el-select v-model="editData.type" placeholder="请选择员工类型">
          <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工姓名" prop="empName" required>
        <el-input v-model="editData.empName"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <!--        <el-input v-model="editData.sex"></el-input>-->
        <el-select v-model="editData.sex" placeholder="请选择员工类型">
          <el-option
              v-for="item in sexOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工照片" prop="photo">
        <el-input v-model="editData.photo"></el-input>
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/common/upload"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="headers"
        >
          <div v-if="editData.photo">
            <img :src="editData.photo" class="el-upload-list__item-thumbnail preview-image"
                 alt=""/>
            <div class="photo-actions">
              <el-button size="mini" type="danger" @click="deleteEditDataPhoto" icon="el-icon-delete" circle>删除
              </el-button>
            </div>
          </div>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="电话" prop="empPhone">
        <el-input v-model="editData.empPhone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editData.email"></el-input>
      </el-form-item>
      <el-form-item label="入职时间" prop="hireTime" required>
        <div class="block">
          <span class="demonstration"></span>
          <el-date-picker
              v-model="editData.hireTime"
              type="date"
              placeholder="Pick a day"
              value-format="YYYY-MM-DD"
          />
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input v-model="editData.note"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="editEmployee" :loading="isSaving">保存</el-button>
    </template>
  </el-dialog>
</template>


<!-- 新增对话框 -->
<script setup>
// 导入请求模块
import {addEmployeeService, deleteEmployeeService, getEmployeePageService, updateEmployeeService} from "@/api/employee";
import {getRegisterDataService} from "@/api/common";
// 导入vue组件
import {reactive, ref, toRaw} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import MessageBox2 from "@/components/MessageBox2.vue"

// 导入store
import {employeesStore} from "@/stores/modules/employee"
import {Plus} from "@element-plus/icons-vue";
// 获取store 数据
const employeeStore = employeesStore()

// 表格参数
const tableTitle = "职员信息"
const tableTitleList = {
  empId: "职员编号",
  account: "账号",
  password: "密码",
  type: "类型",
  empName: "职员名称",
  sex: "性别",
  empPhone: "电话号码",
  email: '邮箱',
  hireTime: "入职时间",
  note: "备注"
}
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const account1 = ref("")
const empName = ref("")

// 查询函数
const search = () => {
  getEmployeePage(currentPage, pageSize, empName, account1)
}
//页面变化 + 条件变化
const getEmployeePage = async (currentPage, pageSize, empName, account) => {
  loading.value = true

  console.log(currentPage, pageSize, empName, account)
  try {
    const res = await getEmployeePageService(currentPage.value, pageSize.value, empName.value, account.value)
    if (res.status === 200) {
      employeeStore.setEmployees(res.data.data.records)
      total.value = res.data.data.total
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  } finally {
    loading.value = false
  }
}
//子组件触发
const currentPageChange = (cP) => {
  currentPage.value = cP
  getEmployeePage(currentPage, pageSize, empName, account1)
}
const pageSizeChange = (size) => {
  pageSize.value = size
  getEmployeePage(currentPage, pageSize, empName, account1)
}

// 管理注册的数据
const addVisble = ref(false)
const regData = ref([])

const getRegData = () => {
  getRegisterDataService()
      .then(res => {
        console.log(res)
        if (res.status === 200) {
          regData.value = res.data.data
        } else {
          ElMessageBox.alert('获取注册数据失败', '错误', {});
        }
      })
      .catch(e => {
        ElMessageBox.alert(e.message, '错误', {});
      })
      .finally(() => {
      });
}
const handleRegisterData = () => {
  addVisble.value = !addVisble.value
  getRegData()
};
// 根据 type 返回角色名称
const getRoleName = (type) => {
  const roleMap = {
    1: '销售管理员',
    2: '销售人员',
    3: '仓库管理员'
  };
  return roleMap[type] || '未知角色'; // 默认值是 '未知角色'
};

// 新增员工信息
const addDialogVisible = ref(false)
const newEmployee = reactive({
  account: "",
  password: "",
  type: "",
  empName: "",
  sex: "",
  photo: "",
  empPhone: "",
  email: '',
  hireTime: "",
  note: ""
})
const isAdding = ref(false)
const optionName = ref('')
const sexOptions = ref([
  {
    value: 'male',
    label: '男',
  },
  {
    value: 'female',
    label: '女',
  }
])

const typeOptions = ref([
  {
    value: '1',
    label: '销售管理员',
  },
  {
    value: '2',
    label: '销售人员',
  },
  {
    value: '3',
    label: '仓库管理员',
  }
])
const onAddOption = () => {
  isAdding.value = true
}

const onConfirm = () => {
  if (optionName.value) {
    sexOptions.value.push({
      label: optionName.value,
      value: optionName.value,
    })
    clear()
  }
}

const clear = () => {
  optionName.value = ''
  isAdding.value = false
}

// 新增员工
const openAddDialog = () => {
  addDialogVisible.value = true
}
const saveEmployee = async () => {
  try {
    const res = await addEmployeeService(newEmployee)
    console.log(res)
    if (res.status === 200) {
      await ElMessageBox.alert('新增客户成功', '成功', {});
      await getEmployeePage(currentPage, pageSize, empName, account1)
      addDialogVisible.value = false
    } else {
      await ElMessageBox.alert('新增客户失败', '错误', {});
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  }
}

//编辑员工
const flag = ref(0)
const editDialogVisible = ref(false)
const editData = ref({})
const isSaving = ref(false); // 用于保存按钮的加载状态
const openEditDialog = (row, index) => {
  editData.value = {...row}
  editDialogVisible.value = true
  flag.value = index
}
const editEmployee = async () => {
  try {
    isSaving.value = true;
    let res
    if (flag.value === 0) {
      res = await updateEmployeeService(toRaw(editData.value))
    } else if (flag.value === 1) {
      res = await addEmployeeService(toRaw(editData.value))
    }

    if (res.status === 200) {
      getRegData()
      await ElMessageBox.alert('编辑客户成功', '成功', {})
      await getEmployeePage(currentPage, pageSize, empName, account1)
      editDialogVisible.value = false
    } else {
      await ElMessageBox.alert('编辑客户失败', '错误', {});
    }
  } catch (e) {
    await ElMessageBox.alert(e.message, '错误', {});
    console.log(e)
  } finally {
    isSaving.value = false;
  }
}

//编辑照片
const deleteEditDataPhoto = () => {
  editData.value.photo = ""
}

// 删除客户
// 状态控制
const batchMode = ref(false); // 是否启用批量模式
const selectedRows = ref([]); // 存储选中的行数据
// 切换批量操作模式
const toggleBatchMode = () => {
  batchMode.value = !batchMode.value;
  if (!batchMode.value) {
    selectedRows.value = []; // 清空选中数据
  }
};
// 更新选中的行数据
const updateSelectedRows = (rows) => {
  selectedRows.value = rows;
};
// 批量删除逻辑
const handleBatchDelete = async () => {
  const ids = selectedRows.value.map((row) => row.empId);
  try {
    const res = await deleteEmployeeService(ids);
    if (res.status === 200) {
      employeeStore.employees = employeeStore.employees.filter(
          (item) => !ids.includes(item.empId)
      );
      toggleBatchMode();
    }
  } catch (error) {
    console.error(error);
  }
  getEmployeePage(currentPage, pageSize, empName, account1)
};
const deleteEmployee = async (id) => {
  const res = await deleteEmployeeService(id)
  if (res.status === 200) {
    employeeStore.employees = employeeStore.employees.filter(item => item.empId !== id)
    ElMessage.success('删除成功')
  }
  getEmployeePage(currentPage, pageSize, empName, account1)
}

// 上传照片
const handleAvatarSuccess = (fileUrl) => {
  // console.log(fileUrl)
  newEmployee.photo = fileUrl.data
  editData.value.photo = fileUrl.data
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
}
const headers = {
  token: localStorage.getItem('token'), // 如果需要 token 验证
};
const deletePhoto = () => {
  newEmployee.photo = ""
}
const handlePhotoError = () => {
  ElMessage.error('上传头像图片失败!');
}


// 初始化
console.log("初始化")
getEmployeePage(currentPage, pageSize, empName, account1)
console.log("初始化结束")

</script>


<style scoped>
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.preview-image {
  width: 100px; /* 设置宽度 */
  height: 100px; /* 设置高度 */
  object-fit: cover; /* 保持图片比例裁剪适配 */
  border-radius: 4px; /* 如果需要圆角 */
}

.photo-container {
  position: relative;
  width: 100px;
  height: 100px;
}

.photo-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  border-radius: 4px;
  cursor: pointer;
}

.photo-preview {
  position: relative;
  width: 100%;
  height: 100%;
}

.photo-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  display: flex;
  gap: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: #baaeb5 1px dashed;
}

</style>